/*
 * @(#)FileUtil.java	 May 18, 2012
 *
 * Copyright 2004-2012 WXXR Network Technology Co. Ltd. 
 * All rights reserved.
 * 
 * WXXR PROPRIETARY/CONFIDENTIAL.
 */

package com.ykdl.member.kid.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

import com.ykdl.member.base.QLog;

/**
 * 文件工具类
 * @author spring sky
 *
 */
public class FileUtil {
    /**
     * 获取目录名称
     * @param url
     * @return FileName
     */
    public static String getFileName(String url)
    {
        int lastIndexStart = url.lastIndexOf("/");
        if(lastIndexStart!=-1)
        {
            return url.substring(lastIndexStart+1, url.length());
        }else{
            return new Timestamp(System.currentTimeMillis()).toString();
        }
    }
    /**
     * 判断SD卡是否存在
     * @return boolean
     */
    public static boolean checkSDCard() {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * 保存目录目录到目录
     * @param context
     * @return  目录保存的目录
     */
    public static String setMkdir(Context context)
    {
        String filePath = null;
        if(checkSDCard())
        {
            filePath = Environment.getExternalStorageDirectory()+File.separator+"downloads";
        }else{
            filePath = context.getCacheDir().getAbsolutePath()+File.separator+"downloads";
        }
        File file = new File(filePath);
        if(!file.exists())
        {
            file.mkdirs();
            Log.e("file", "目录不存在   创建目录    ");
        }else{
            Log.e("file", "目录存在");
        }
        return filePath;
    }
    
    public static boolean isFileExists(String path){
    	QLog.debug("isFileExists======", path);
    	if(path.startsWith("file://")){
    		path=path.substring(8);
    	}
    	File f=new File(path);
    	return f.exists();
    }
    
    
    
    /**
     * 获取路径
     * @return
     * @throws IOException
     */
    public static  String getPath(Context context)
    {
        String path = null;
        try {
            path = FileUtil.setMkdir(context)+File.separator+ "lmyr.apk";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }
    
    public static  String getDownAPKFilePath(Context context)
    {
        String path = null;
        try {
            path = FileUtil.setMkdir(context)+File.separator+ "lmyr.apk";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }
    
    /**
     * 获取文件的大小
     * 
     * @param fileSize
     *            文件的大小
     * @return
     */
    public static String FormetFileSize(int fileSize) {// 转换文件大小
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileSize < 1024) {
            fileSizeString = df.format((double) fileSize) + "B";
        } else if (fileSize < 1048576) {
            fileSizeString = df.format((double) fileSize / 1024) + "K";
        } else if (fileSize < 1073741824) {
            fileSizeString = df.format((double) fileSize / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileSize / 1073741824) + "G";
        }
        return fileSizeString;
    }
    
    
    public static String[] getImagePath(Context mContext,String path){
    	String fileUrione = Environment.getExternalStorageDirectory()
				.toString() + path;
    	String fileName = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date())+".jpg";// 照片命名
		File out = new File(fileUrione);
		if (!out.exists()) {
			out.mkdirs();
		}	
    	return new String[]{fileUrione,fileName};
    }
    
    public static long getAvailaleSize(){
    	try{

    	File path = Environment.getExternalStorageDirectory(); //取得sdcard文件路径

    	StatFs stat = new StatFs(path.getPath()); 

    	 

    	long blockSize = stat.getBlockSize(); 

    	 

    	long availableBlocks = stat.getAvailableBlocks();

    	 

    	return availableBlocks * blockSize/1024/1024; 

    	//(availableBlocks * blockSize)/1024      KIB 单位

    	//(availableBlocks * blockSize)/1024 /1024  MIB单位

    	}catch(Exception ee){
    		
    	}
        return -1;
    	}
    
    
    
    /**
     * 从文件中直接读一个对象
     * @param fileName
     * @return
     */
    public synchronized static Object readSerObjectFromFile(String fileName){ 
		Object b = null;
		ObjectInputStream in = null;
		try {
			in = new ObjectInputStream(new FileInputStream(
					fileName));
			b = in.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return b;
	}
    public synchronized static void saveSerObjectToFile(Object object, String fileName){
		ObjectOutputStream out = null;
		try {
			makeDIRAndCreateFile(fileName);
			out = new ObjectOutputStream(
				      new FileOutputStream(fileName));
			out.writeObject(object);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
    
    
    public static synchronized File makeDIRAndCreateFile(String filePath) throws IOException {
		
		if(filePath == null || "".equals(filePath)) {
			return null;
		}
		File file = new File(filePath);
		String parent = file.getParent();
		File parentFile = new File(parent);
		if (!parentFile.exists()) {
			if (parentFile.mkdirs()) {
				file.createNewFile();
			} else {
				throw new IOException("创建目录失败！");
			}
		} else {
			if (!file.exists()) {
				file.createNewFile();
			}
		}
		return file;
	}
	public static void copyFile(String src, String des) {
		try{
		File sourceFile=new File(src);
		File targetFile=new File(des);
		if(!targetFile.exists()){
			targetFile.createNewFile();
		}
		        BufferedInputStream inBuff = null;
		        BufferedOutputStream outBuff = null;
		        try {
		            // 新建文件输入流并对它进行缓冲
		            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

		            // 新建文件输出流并对它进行缓冲
		            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

		            // 缓冲数组
		            byte[] b = new byte[1024 * 5];
		            int len;
		            while ((len = inBuff.read(b)) != -1) {
		                outBuff.write(b, 0, len);
		            }
		            // 刷新此缓冲的输出流
		            outBuff.flush();
		        } finally {
		            // 关闭流
		            if (inBuff != null)
		                inBuff.close();
		            if (outBuff != null)
		                outBuff.close();
		        }
		  
		}catch(Exception ee){
			QLog.debug("ff", "fff");
		}
	}
	
	public static String setFilePath(Context context)
    {
        String filePath = null;
        if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        {
            filePath = Environment.getExternalStorageDirectory()+File.separator + "lmyr/apk/down/";
        }else{
            filePath = context.getCacheDir().getAbsolutePath()+File.separator + "lmyr/apk/down/";
        }
        File file = new File(filePath);
        if(!file.exists())
        {
            file.mkdirs();
        }
        return filePath;
    }
}
